#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'xnevergreen'
__mtime__ = '2015-12-23'
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃  永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

# 1.登录
# http://www.alimama.com/member/login.htm?forward=http%3A%2F%2Fad.alimama.com%2Findex.htm
#
# 2.搜索待推广产品
# http://pub.alimama.com/promo/search/index.htm?q=https%3A%2F%2Fdetail.tmall.com%2Fitem.htm%3Fid%3D540666582758&_t=1489744519080http://pub.alimama.com/promo/search/index.htm?q=https%3A%2F%2Fdetail.tmall.com%2Fitem.htm%3Fid%3D535689509798&_t=1490242897517
#
# 3.模拟点击推广

from urllib import urlencode
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pickle
import requests
import re, time, sys, os, json, random, string

# 去除ssl的警告信息
# from requests.packages.urllib3.exceptions import InsecureRequestWarning
# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

username = 'xxx'
password = 'xxx'

query = {'q': 'http://item.taobao.com/item.htm?id=535689509798'}

UA = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"

LOGIN_URL = 'http://www.alimama.com/member/login.htm?forward=http%3A%2F%2Fad.alimama.com%2Findex.htm'
SEARCH_URL = 'http://pub.alimama.com/promo/search/index.htm?{QUERY}'

LOGIN_TEXT = 'site-nav-orange' # 顶部登录文字连接
LOGIN_IFRAME = '"taobaoLoginIfr"' # 登录iframe名称
PASSWORD_LOGIN_SWITCH_BUTTON = 'J_Quick2Static' # 密码登录
LOGIN_USERNAME = 'TPL_username_1' # 用户名
LOGIN_PASSWORD = 'TPL_password_1' # 密码
LOGIN_BUTTON = 'J_SubmitStatic' # 登录按钮


# 获取脚本所在真实目录
strfilepath = os.path.realpath(__file__)
COOKIE_PATH = "%s/" % (os.path.dirname(strfilepath),)
COOKIEFILE = COOKIE_PATH + "tmp/cookie_" + username

def getTime():
    return str(int(time.time()))

# 初始化浏览器
s = requests.session()
sel = webdriver.Chrome()
# sel = webdriver.PhantomJS()
delay = 10

SEARCH_URL = SEARCH_URL.replace('{QUERY}', urlencode(query))
LOGIN_URL = SEARCH_URL

if os.path.exists(COOKIEFILE):

    sel.get(SEARCH_URL)

    # 存在cookie则更新cookie
    cookie = {}
    cookies = pickle.load(open(COOKIEFILE, "rb"))
    print cookies
    # 转化selenium的cookie为request所使用的cookie
    for cookie in cookies:
        sel.add_cookie(cookie)

    sel.get(SEARCH_URL)
    sel.quit()

else:

    sel.maximize_window()
    # sel.set_window_size(240, 320)
    # open the login in page
    sel.get(LOGIN_URL)
    try:
        # 等待登录文字连接出现
        element_login_text = EC.presence_of_element_located((By.CLASS_NAME, LOGIN_TEXT))
        WebDriverWait(sel, delay).until(element_login_text)

        # 点击文字登录连接
        sel.find_element(By.CLASS_NAME, LOGIN_TEXT).click()

        # 等待登录iframe出现
        element_login_iframe = EC.presence_of_element_located((By.NAME, LOGIN_IFRAME))
        WebDriverWait(sel, delay).until(element_login_iframe)

        # 切换进iframe
        sel.switch_to.frame(sel.find_element_by_xpath('//*[@id="J_login_panel_taobao"]/iframe'))

        # 等待切换普通密码登录图标出现
        element_present = EC.presence_of_element_located((By.ID, PASSWORD_LOGIN_SWITCH_BUTTON))
        WebDriverWait(sel, delay).until(element_present)

        # 切换进普通密码登录
        sel.find_element(By.ID, PASSWORD_LOGIN_SWITCH_BUTTON).click()
        # 回填用户名和密码
        sel.find_element(By.ID, LOGIN_USERNAME).send_keys(username)
        sel.find_element(By.ID, LOGIN_PASSWORD).send_keys(password)
        # sel.find_element(By.ID, LOGIN_BUTTON).click()

        # sel.switch_to.frame("taobaoLoginIfr")
        # element_present = EC.presence_of_element_located((By.ID, PASSWORD_LOGIN_SWITCH_BUTTON))
        # WebDriverWait(sel, delay).until(element_present)
        # sel.find_element(By.ID, PASSWORD_LOGIN_SWITCH_BUTTON).click()
        # sel.find_element(By.ID, LOGIN_USERNAME).send_keys(username)
        # sel.find_element(By.ID, LOGIN_PASSWORD).send_keys(password)
        # sel.find_element(By.ID, LOGIN_BUTTON).click()
        sys.exit()

        # 验证登录成功与否，若currenturl发生变化，则认为登录成功
        curpage_url = sel.current_url
        print curpage_url
        while (curpage_url == LOGIN_URL):
            try:
                print 'login button click success - (^_^)'
            except:
                print 'login button click fail - (X_X)'
            time.sleep(3)
            curpage_url = sel.current_url

        # wait = WebDriverWait(sel, 10)
        print sel.current_url
        # wait.until(lambda sel: sel.current_url != "http://ad.alimama.com/index.htm")

        pickle.dump(sel.get_cookies(), open(COOKIEFILE, "wb"))

    except TimeoutException:
        print "Loading took too much time!"
    # finally:
    #     sel.quit()

def getTime():
    return str(int(time.time()))